import Vue from 'vue'
import userApi from '@/api/user';
let state = { 
    userData : JSON.parse(window.localStorage.getItem('userData')) || '',
    userRouters:[],
    userPermissions : [],
    menu:[]
};

const mutations = {
    SET_USERDATA: function(state, userData) {
        window.localStorage.setItem('userData',JSON.stringify(userData))
        state.userData = userData;
    },
    SET_USERROUTERS: function(state, userRouters) {
      state.userRouters = userRouters;
    },
    SET_USERPERMISSIONS: function(state, userPermissions) {
      state.userPermissions = userPermissions;
    },
    SET_MENU: function(state,menu){
      state.menu = menu
    }
};
const getters = {
    GET_USERDATA: function(state){
        return state.userData
    },
    GET_USERROUTERS: function(state){
      return state.userRouters
    },
    GET_USERPERMISSIONS: function(state){
      return state.userPermissions
    },
    GET_MENU: function(state){
      return state.menu
    },
};
const actions = {
  login:function({commit},userData){
    const { userInfo, userRouters, userPermissions} = userData
    commit('SET_USERDATA', userInfo);
    commit('SET_USERROUTERS', userRouters);
    commit('SET_USERPERMISSIONS', userPermissions);
  },
  logout:function({commit}){
    commit('SET_USERDATA', {});
    commit('SET_USERROUTERS', []);
    commit('SET_USERPERMISSIONS', []);
    commit('SET_MENU', []);
  },
  getUserRouters:function({commit}){
    return userApi.getUserRouters({id:state.userData.id}).then((res)=>{
      if(res.code == 200){
        commit('SET_USERROUTERS', res.userRouters);
      }
    })
  },
  setMenu:function({commit},menu){
    commit('SET_MENU', menu);
  }
};
export default{
    state,
    mutations,
    actions,
    getters
}